<template>
  <div>
    <div
      class="text-danger mb10"
      v-if="enableDataScope && mode == 'design'"
    >
      {{ $t("formgen.deptSelect.dataScopeDesc") }}
      （{{ $t("formgen.deptSelect.dataScopeDesc_2") }}）
    </div>
    <el-input
      v-model="showValue"
      :disabled="props.disabled"
      prefix-icon="ele-User"
      class="select-user-input"
      :readonly="props.readonly"
      @change="handleInputChange"
    />
  </div>
</template>

<script lang="ts" name="TUserSelect" setup>
import { onMounted, ref, defineProps, useAttrs } from "vue";
import { getEmpTreeRequest } from "../../../api";
import { formEmits, formItemProps, useFormItem } from "../hooks/useFormItemHook";
import { useUserInfo } from "@/stores/userInfo";
import { Session } from "@/utils/storage";
import { userInfoKey } from "@/utils/auth";
import { useRoute } from "vue-router";

// const data = ref<any[]>([]);
const showValue = ref("");

const props = defineProps({
  ...formItemProps,
  disabled: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  },
  defaultCurrentUser: {
    type: Boolean,
    default: false
  },
  enableDataScope: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(formEmits);

const { changeValue, updateValue } = useFormItem(props, emits, true);

const handleInputChange = (val: any) => {
  console.log(val);
  changeValue.value = val;
  updateValue(val);
};

const userInfoStore = useUserInfo();

const dataLoading = ref(false);

const attrs = useAttrs();
const formKey = useRoute().params.key;

onMounted(async () => {
  dataLoading.value = true;
  getEmpTreeRequest({ formKey: formKey, formItemId: attrs.dId }).then((res: any) => {
    dataLoading.value = false;
    console.log("res", res);
    // data.value = res.data;
  });
  console.log("props.value", props.value);
  console.log("props.defaultCurrentUser", props.defaultCurrentUser);
  if (props.value) {
    showValue.value = props.value;
  }
  // 默认值是空的 默认当前用户
  if (props.defaultCurrentUser) {
    // && !props.value TODO: 存在获取登录用户信息 设置的问题 @ chd
    console.log("11", 11);
    const setDefaultUser = (user: any) => {
      console.log("user", user.userName);
      changeValue.value = user.userName;
      showValue.value = user.userName;
      updateValue(changeValue.value);
    };
    if (Session.get(userInfoKey)) {
      const userInfos = Session.get(userInfoKey);
      setDefaultUser(userInfos);
    } else {
      await userInfoStore.getApiUserInfo().then((res: any) => {
        setDefaultUser(res);
      });
    }
  }
});

/**
 * 判断数组是否是空的
 */
const isEmptyArray = (arr: any[]) => {
  return !arr || !arr.length;
};
</script>

<style>
.select-user-input {
  cursor: pointer;
}

.name-input {
  width: 320px;
}

@media screen and (max-width: 768px) {
  .name-input {
    width: 100%;
  }
}
</style>
